<template>  
    <form :method="method" :action="action" ref="gForm" :id="id">
        <slot name="form-item"></slot>
        <slot></slot>
    </form>
    
</template>
<script>
import {ref,onMounted,onUpdated} from 'vue';
export default {
    name:'g-form',
    props:{
        method:{
            type:String,
            default:''
        },
        action:{
            type:String,
            default:''
        },
        id:{
            type:String,
            default:'defaultForm'
        }

    },
    setup(props){
        let gForm = ref(null);
        let data = ref({});
        let id = ref(props.id);
        let getFormData = ()=>{
            // 先清空data的值，防止会对后续操作干扰
            data.value = {};
            // 获取所有带有.form_label选择器的标签
            // let childList = gForm.value.querySelectorAll(".form_label");
            let childList = document.getElementById(id.value).getElementsByClassName("form_label");
            for (const n of childList) {
                if(n.type == 'checkbox' && data.value[n.name] == undefined){
                    data.value[n.name] = [];
                }
                if(n.type == 'checkbox'){
                    if(n.checked){
                        let checkArra = data.value[n.name];
                        console.log("插入值：",n.value)
                        checkArra.push(n.value)
                        data.value[n.name] = checkArra;
                    }
                    
                }else if(n.type == 'radio'){
                    if(n.checked){
                        data.value[n.name] = n.value;
                    }
                }else if(n.type == 'file'){
                    data.value[n.name] = n.files[0];
                }else{
                    if(n.name != undefined){
                        data.value[n.name] = n.value;
                    }
                    
                }
            }
            return data.value;

        }

        onUpdated(()=>{
            data.value = getFormData();
        })
        return {
            gForm,getFormData,data,id
        }
    }
}
</script>
<style>

</style>